package com.lupan.pio;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * 说明：导入excel的工具类
 *
 * @author lupan
 * @version 2016/12/28 14:45
 */
public class ExcelImportUtil {

    public static void importExcel(String filePath) throws IOException, InvalidFormatException {

        if (!filePath.endsWith(".xls") && !filePath.endsWith(".xlsx")) {
            throw new RuntimeException("上传文件不是excel文档！");
        }

        FileInputStream fis;
        try {
            fis = new FileInputStream(filePath);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            throw new RuntimeException("找不到文件！" + filePath);
        }

        //获取excel文档对象
        Workbook workbook=WorkbookFactory.create(fis);
//        if(filePath.endsWith(".xls")){
//            workbook = new HSSFWorkbook(fis);
//        }else{
//            workbook = new XSSFWorkbook(fis);
//        }


        //获取一个工作表
        Sheet sheet = workbook.getSheetAt(0);
        //获取表头
        Row titleRow = sheet.getRow(0);
        for (int i = 0; i < titleRow.getLastCellNum(); i++) {
            System.out.print(titleRow.getCell(i).getStringCellValue() + " ");
        }

        //获取总行数
        int rowCount = sheet.getLastRowNum();
        //获取所有行的数据
        for (int i = 1; i <= rowCount; i++) {
            System.out.println();
            Row row = sheet.getRow(i);
            for (int j = 0; j < row.getLastCellNum(); j++) {
                Cell cell = row.getCell(j);
                String value = cell.getStringCellValue();
                System.out.print(value + " ");
            }
        }
    }
}
